package xyz.coolcsm.security.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import xyz.coolcsm.security.config.JsonResult;
import xyz.coolcsm.security.config.ResultTool;
import xyz.coolcsm.security.config.RsaKeyProperties;
import xyz.coolcsm.security.entity.*;
import xyz.coolcsm.security.service.CommentService;
import xyz.coolcsm.security.service.QuestionCategoryService;
import xyz.coolcsm.security.service.QuestionService;
import xyz.coolcsm.security.service.RedisService;
import xyz.coolcsm.security.utils.JwtUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
 * @author 什锦
 * @since 2021-06-1
 */

@RestController
public class QuestionController {

    @Autowired
    QuestionCategoryService questionCategoryService;
    @Autowired
    QuestionService questionService;
    @Autowired
    private RsaKeyProperties prop;
    @Autowired
    CommentService commentService;
    @Autowired
    RedisService redisService;


    //个人发布问题分类
    @GetMapping("/api/question/{limit}/{page}")
    public JsonResult questionListPageByuser(HttpServletRequest request,@PathVariable("page") int page,@PathVariable("limit") int limit){
        //获取个人信息
        String token = request.getHeader("Authorization");
        Payload<SysUser> payload = null;
        payload = JwtUtils.getInfoFromToken(token.replace("Bearer ", ""),
                        prop.getPublicKey(), SysUser.class);
        if (page < 1){
            page = 1;
        }
        //先查询缓存
        String key = "redis:questionUser:" +page+payload.getUserInfo().getId();
        Object object = redisService.get(key);
        //缓存为空，从数据库查询，并存入redis
        if (object == null){
            Page<Question> pageParam = new Page<>(page, limit);
            questionService.page(pageParam,new QueryWrapper<Question>().orderByDesc("create_time").eq("author_id",payload.getUserInfo().getId()));
            redisService.set(key,pageParam,60*60);
            return ResultTool.success(pageParam);
        }
        //查询成功，返回结果
        Page<Question> questionPage = (Page<Question>) object;
        return ResultTool.success(questionPage);
    }


    //首页问题分类
    @PostMapping("/api/question/{limit}/{page}")
    public JsonResult questionListPage(@PathVariable("page") int page,@PathVariable("limit") int limit){
        if (page < 1){
            page = 1;
        }
        //先从缓存查询
        String key = "redis:question:" +page;
        Object object = redisService.get(key);
        //缓存为空，从数据库查询
        if (object == null){
            Page<Question> pageParam = new Page<>(page, limit);
            questionService.page(pageParam,new QueryWrapper<Question>().orderByDesc("create_time"));
            redisService.set(key,pageParam,60*60);
            return ResultTool.success(pageParam);
        }
        //查询成功，返回结果
        Page<Question> questionPage = (Page<Question>) object;
        return ResultTool.success(questionPage);
    }

    //问题详情
    @GetMapping("/api/question/details/{id}")
    public JsonResult questionDetails(@PathVariable("id") int id){
        //先从缓存查询
        String key = "redis:questionDetails:" +id;
        Object object = redisService.get(key);
        //缓存不存在，从数据库查询，更新浏览量
        if (object == null){
            Question question = questionService.getById(id);
            int i = question.getViews() + 1;
            question.setViews(i);
            questionService.updateById(question);
            redisService.set(key,question,60*60);
            return ResultTool.success(question);
        }
        //更新浏览量，返回结果
        Question question = (Question)object;
        int i = question.getViews() + 1;
        question.setViews(i);
        questionService.updateById(question);
        redisService.set(key,question,60*60);
        return ResultTool.success(question);
    }

    //问题分类
    @GetMapping("/api/question/questionCategory")
    public JsonResult questionCategory(){
        String key = "redis:questionCategory:" +1;
        Object object = redisService.get(key);
        if (object == null){
            List<QuestionCategory> list = questionCategoryService.list();
            redisService.set(key,list);
            return ResultTool.success(list);
        }
        List<QuestionCategory> list = (List<QuestionCategory>)object;
        return ResultTool.success(list);
    }


    //新增或修改问题
    @PostMapping("/api/question/issueQuestion")
    public JsonResult issueQuestion(HttpServletRequest request, @RequestBody Question question ){
        String token = request.getHeader("Authorization");
        Payload<SysUser> payload = JwtUtils.getInfoFromToken(token.replace("Bearer ", ""),
                        prop.getPublicKey(), SysUser.class);
        SysUser sysUserInfo = payload.getUserInfo();
        //先删除缓存
        if (question.getId() != null){
            String key = "redis:questionDetails:" +question.getId();
            redisService.del(key);
        }
        for (int i = 1;i<100;i++){
            String key = "redis:questionUser:" +i+payload.getUserInfo().getId();
            String key1 = "redis:question:" +i;
            redisService.del(key);
            redisService.del(key1);
        }
        //更新数据库
        question.setAuthorId(sysUserInfo.getId().toString());
        question.setAuthorAvatar(sysUserInfo.getAvatar());
        question.setAuthorName(sysUserInfo.getNickName());
        questionService.saveOrUpdate(question);
        //再一次删除数据库
        for (int i = 1;i<100;i++){
            String key = "redis:questionUser:" +i+payload.getUserInfo().getId();
            String key1 = "redis:question:" +i;
            redisService.del(key);
            redisService.del(key1);
        }
        if (question.getId() != null){
            String key = "redis:questionDetails:" +question.getId();
            redisService.del(key);
        }
        return ResultTool.success();
    }

    //删除问题
    @DeleteMapping("/api/user/question/delete/{qid}")
    public JsonResult delete(HttpServletRequest request,@PathVariable("qid") String qid){
        //获取个人信息
        String token = request.getHeader("Authorization");
        Payload<SysUser> payload = null;
        payload = JwtUtils.getInfoFromToken(token.replace("Bearer ", ""),
                prop.getPublicKey(), SysUser.class);
        String key2 = "redis:questionDetails:" +qid;
        redisService.del(key2);
        for (int i = 1;i<100;i++){
            String key = "redis:questionUser:" +i+payload.getUserInfo().getId();
            String key1 = "redis:question:" +i;
            redisService.del(key);
            redisService.del(key1);
        }
        Boolean flag =questionService.remove(new QueryWrapper<Question>().eq("id", qid).eq("author_id",payload.getUserInfo().getId()));
        if ( flag == false){
            return ResultTool.fail();
        }
        //删除成功再一次删除缓存
        commentService.remove(new QueryWrapper<Comment>().eq("qid",qid).eq("topic_category","1"));
        redisService.del(key2);
        for (int i = 1;i<100;i++){
            String key = "redis:questionUser:" +i+payload.getUserInfo().getId();
            String key1 = "redis:question:" +i;
            redisService.del(key);
            redisService.del(key1);
        }
        return ResultTool.success();
    }

}
